from datetime import *
from flask import Blueprint,request,jsonify
import requests
from conf.comm import sqlalchemy_context
from database import *
from werkzeug.security import generate_password_hash,check_password_hash
from utils.comm import send_message
from utils.rediscoon import r
from utils.jwt_token import myjwt
from utils.myupyun import myyun
from utils.myfile import myfile
import json
import re
import random
import time
import os
import uuid
#蓝图初始化
bp_users = Blueprint('users',__name__)
#注册功能实现
@bp_users.route('/reg',methods=['POST','GET'])
@sqlalchemy_context()
def reg():
    if request.method == 'POST':
        data = request.data
        if not data:
            data = request.form
        else:
            
            data = json.loads(request.data)

        
        if not re.match('^1[3-9]\d{9}$', data['mobile']):
            return jsonify({'code':10012})

        try:
            
            username = data['username']
            password = data['password']
            mobile = data['mobile']
            user = User(username=username,password=generate_password_hash(password),mobile=mobile)
            db.session.add(user)
            db.session.commit()
            return jsonify({'code':200})
        except:
            return jsonify({'code':10010})

#发送验证码
@bp_users.route('/login',methods=['POST','GET'])
@sqlalchemy_context()
def login():

    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(request.data)
        else:
            data = request.form
        mobile = data['mobile']
        #判断是否为空
        if not mobile:
            return jsonify({'code':20010,'mes':'必须输入正确的手机号'})
        #判断格式是否正确
        if not re.match('^1[3-9]\d{9}$',mobile):
            return jsonify({'code':20016,'mes':'手机号格式不正确'})
    
          
        codes = r.get_str(mobile)
        if codes:
            return jsonify({'code':20011,'mes':'60秒内不能再发了'})
        
        #生成6位数
        code = random.randint(100000, 999999)
        flag = send_message(mobile, code, 1) 
        if flag:
            r.set_str(mobile,60,code)
            return jsonify({'code':200,'codes':code})
        else:
            return jsonify({'code':20012,'mes':'发送失败'})

#用户名密码登录
@bp_users.route('/login1',methods=['POST','GET'])
@sqlalchemy_context()
def login1():
    data=json.loads(request.data)
    username = data['username']
    password = data['password']
    user = User.query.filter_by(username=username).first()
    if user:
        if check_password_hash(user.password,password):
            token = myjwt.encode_jwt({'id':user.id})
            return jsonify({'code':200,'token':token,'userid':user.id,'username':user.username})
        else:
            #密码失败后
            #先根据username判断之前是否已经错误过
            record = Record.query.filter_by(username=username).first()
            #如果没有的话，就往表里添加东西
            if not record:
                record = Record(username=username,count=1)
                db.session.add(record)
                db.session.commit()
            else:
                #如果有的话
                #先获取下当前时间，再获取当时登录错误的时间
                #timestamp 转一下秒，除以3600，变成小时
                time1 = datetime.datetime.now()
                time2 = record.losertime.timestamp()/3600
                #如果 时间大于24，就把次数变成0 再次进行操作
                if time1.timestamp()/3600 - time2 >24:
                    Record.query.filter_by(username=username).update({'count':0,'losertime':time1})
                    db.session.commit()
                
                if record.count <3:
                    Record.query.filter_by(username=username).update({'count':record.count+1})
                    db.session.commit()
                else:
                    return jsonify({'code':20017,'mes':'今日已三次'})

            return jsonify({'code':20014,'mes':'密码错误'})
    else:
        return jsonify({'code':20015,'mes':'用户名错误'})

    


#手机号登录
@bp_users.route('/login2',methods=['POST'])
@sqlalchemy_context()
def login2():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    mobile = data['mobile']
    codes = data['codes']
    code = r.get_str(mobile)
    if re.match('^1[3-9]\d{9}$',mobile):
        if code:
            if str(codes) == (code):
                user = User.query.filter_by(mobile=mobile).first()
                if not user:
                    user = User(username=mobile,mobile=mobile)
                    db.session.add(user)
                    db.session.commit()
                r.del_str(mobile)
                token = myjwt.encode_jwt({'id':user.id})
                return jsonify({'code':200,'userid':user.id,'token':token,'username':user.username})
            else:
                return jsonify({'code':20013,'mes':'验证码不正确'})
        
        else:
            return jsonify({'code':20014,'mes':'验证码发送失败'})
    else:
        return jsonify({'code':20015,'mes':'手机号格式不正确'})


@bp_users.route('/get_info',methods=['GET'])
def get_info():
    id = request.args.get('userid')
    user = User.query.filter_by(id=id).first()
    dict1 = {}
    dict1['id'] = user.id
    dict1['username'] = user.username
    dict1['mobile'] = user.mobile
    dict1['pic'] = user.pic
    return jsonify({'code':200,'user':dict1})

@bp_users.route('/upload',methods=['POST'])
def upload():
    #获取文件
    file = request.files['file']
    #获取文件后缀 通过下标
    filetest = os.path.splitext(file.filename)[1]
    #防止覆盖  用uuid加上后缀重命名
    newfile = uuid.uuid4().hex+filetest
    #获取userid
    userid = request.form.get('userid')

    path = './static/upload/'+str(userid)
    if not os.path.exists(path):
        os.mkdir(path)


    #保存到创建的文件夹下
    file.save(os.path.join('./static/upload/'+userid,newfile))
    User.query.filter_by(id=userid).update({'pic':newfile})
    db.session.commit()
    myyun.putyun('./static/upload/'+userid+'/'+newfile,newfile,userid)
    #返回给前端  展示用
    return jsonify({'code':200,'filename':newfile})

@bp_users.route('/get_file',methods=['GET','DELETE'])
def get_file():
    if request.method == 'GET':
        id = request.args.get('userid')
        lists = myfile.show_file(id)
        filelist=[]
        for i in lists:
            dict1 = {}
            dict1['name'] = i
            dict1['url'] = 'http://localhost:5000/static/upload/'+str(id)+'/'+str(i)

            filelist.append(dict1)

        return jsonify({'code':200,'list':filelist})
    
    elif request.method == 'DELETE':
        
        id = request.args.get('userid')
        filename = request.args.get('name')
        try:  
            myfile.remove_file(id,filename)
            return jsonify({'code':200})
        except:
            return jsonify({'code':20010})



bp_users.before_request
def before_request():
    print(request.path)
    list = ['users/get_info']
    if request.path in list:
        try:
            token = request.headers['Token']
        except:
            return jsonify({'code':403,'mes':'请传递token'})
        newtoken = myjwt.decode_jwt(token)
        print(token,newtoken)
        if newtoken and myjwt.check(token,newtoken):
            pass
        else:
            return jsonify({'code':403,'mes':'token错误'})
